package com.xifan.commons.cores.result;

import cn.hutool.core.util.StrUtil;
import com.xifan.commons.cores.constant.FacadeConstants;
import com.xifan.commons.cores.validate.BeanValidators;
import com.xifan.commons.cores.validate.group.GidGroup;
import com.xifan.commons.cores.validate.group.OperatorGroup;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.groups.Default;
import java.io.Serializable;

/**
 * 所有请求都需继承 该抽象类 demo：com.xifan.commons.demo.RequestDTOCheckDemo
 * 追忆寻梦
 * rundreams.net
 *
 * @Author:zzh rundreams@yeah.net  @Time:2020/2/12 0012
 */
@Getter
@Setter
@Slf4j
public abstract class AbstractRequestDTO implements Serializable {

    private static final long serialVersionUID = 6224907758272819065L;

    /**
     * 全局流水号
     */
    @NotNull(groups = GidGroup.class)
    @Size(min = FacadeConstants.GID_LENGTH, max = FacadeConstants.GID_LENGTH, groups = GidGroup.class)
    private String gid;

    /**
     * 操作人用户ID
     */
    @NotNull(groups = {OperatorGroup.class})
    private String operatorId;

    /**
     * 操作人用户名
     */
    @NotNull(groups = {OperatorGroup.class})
    private String operatorName;

    /**
     * 是否校验GID,根据业务场景使用
     */
    protected abstract boolean isValidGid();

    /**
     * 提供给外部调用
     */
    public abstract void valid();

    /**
     * JSR303校验
     */
    protected final void validate(Object object, Class<?>... groups) {

        if (0 == groups.length) {
            groups = ArrayUtils.add(groups, Default.class);
        }

        // gid.
        if (isValidGid()) {
            groups = ArrayUtils.add(groups, GidGroup.class);
        }

        // 校验.
        String errorMessages = BeanValidators.validateWithString(object, groups);

        if (StrUtil.isNotBlank(errorMessages)) {
            log.error("303校验失败返回信息errorMessages={}", errorMessages);
            throw new IllegalArgumentException(errorMessages);
        }
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
}
